﻿using System;
using System.Globalization;
using System.Windows.Controls;
using System.Windows.Data;
using Dsl.Ped.Common.Extensions;

namespace Dsl.Ped.Common.Converters
{
    /// <summary>
    /// Converts a given <see cref="ListBoxItem"/> into its position within the parent <see cref="ListBox"/>
    /// </summary>
    public class ListBoxItemToPositionConverter : IValueConverter
    {
        #region Implementation of IValueConverter

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var itemContainer = (ListBoxItem)value;
            var itemsControl = itemContainer.FindAncestor<ListBox>();

            int addition = 0;
            if (parameter != null)
            {
                int.TryParse(parameter.ToString(), out addition);
            }

            try
            {
                int index = itemsControl.ItemContainerGenerator.IndexFromContainer(itemContainer);
                return index + addition;
            }
            catch (Exception)
            {
                return 0;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
